$(function () {
    // 初始加载
    loadTravelers('');
    // 搜索按钮点击事件
    $(document).on('click', '.search-btn', function () {
        const searchValue = $('.search-input').val().trim();
        loadTravelers(searchValue);
        return false; // 阻止默认行为
    });
    // 搜索框回车事件
    $(document).on('keypress', '.search-input', function (e) {
        if (e.which === 13) {
            const searchValue = $(this).val().trim();
            loadTravelers(searchValue);
            return false; // 阻止默认行为
        }
    });

    function loadTravelers(searchName) {
        showLoading();
        $.ajax({
            url: 'getTraveler',
            method: 'POST',
            data: {search: searchName},
            dataType: 'json',
            success: function (data) {
                hideLoading();
                if (data && data.length > 0) {
                    displayTravelers(data, searchName);
                } else {
                    showEmptyState(searchName);
                }
            }
        });
    }

    function displayTravelers(travelers, currentSearchValue = '') {
        const container = $('.travelers-content');
        let html = '<div class="travelers-header">' +
            '<button class="add-btn" onclick="window.location.href=\'addtravelers.jsp\'">+ 新增常用旅客</button>' +
            '<div class="search-box">' +
            '<input type="text" class="search-input" placeholder="请输入姓名" value="' + currentSearchValue + '">' +
            '<button class="search-btn">搜索</button>' +
            '</div>' +
            '</div>' +
            '<div class="travelers-list">';

        travelers.forEach(traveler => {
            html += '<div class="traveler-item' + (traveler.default ? ' default' : '') + '">' +
                '<div class="traveler-info">' +
                '<div class="name-section">' +
                '<span class="name">' + (traveler.chineseName || '') + ' ' +
                (traveler.surname || '') + ' ' + (traveler.givenName || '') + '</span>' +
                (traveler.default ? '<span class="default-tag">默认</span>' : '') +
                '</div>' +
                '<div class="details">' +
                '<span>性别：' + (traveler.gender || '') + '</span>' +
                '<span>国籍：' + (traveler.nationality || '') + '</span>' +
                '<span>手机：' + (traveler.phone || '') + '</span>' +
                '</div>' +
                '<div class="documents">';

            // 处理证件信息
            if (traveler.documents) {
                traveler.documents.forEach(doc => {
                    html += '<div class="document-item">' +
                        '<span class="doc-type">' + doc.document_type + '：</span>' +
                        '<span class="doc-number">' + doc.document_number + '</span>';

                    if (doc.document_type === '护照') {
                        html += '<span class="doc-expiry">有效期至：' + (doc.expiry_date || '') + '</span>';
                    }

                    html += '</div>';
                });
            }

            html += '</div>' +
                '</div>' +
                '<div class="traveler-actions">' +
                '<button class="edit-btn" onclick="editTraveler(' + traveler.id + ')">编辑</button>' +
                '<button class="delete-btn" onclick="deleteTraveler(' + traveler.id + ')">删除</button>';

            if (!traveler.default) {
                html += '<button class="set-default-btn" onclick="setDefault(' + traveler.id + ')">设为默认</button>';
            }

            html += '</div></div>';
        });

        html += '</div>';
        container.html(html);
    }

    function showEmptyState(currentSearchValue = '') {
        const container = $('.travelers-content');
        let html = '<div class="travelers-header">' +
            '<button class="add-btn" onclick="window.location.href=\'addtravelers.jsp\'">+ 新增常用旅客</button>' +
            '<div class="search-box">' +
            '<input type="text" class="search-input" placeholder="请输入姓名" value="' + currentSearchValue + '">' +
            '<button class="search-btn">搜索</button>' +
            '</div>' +
            '</div>' +
            '<div class="empty-state">' +
            '<p>';

        if (currentSearchValue) {
            html += '没有找到匹配"' + currentSearchValue + '"的旅客';
        } else {
            html += '亲，还没有常用旅客哦，点击按钮进行添加~';
        }

        html += '</p></div>';
        container.html(html);
    }

    window.deleteTraveler = function (id) {
        if (confirm('确定要删除这位旅客吗？')) {
            $.ajax({
                url: 'deleteTraveler',
                method: 'post',
                data: {id: id},
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        alert('删除成功');
                        loadTravelers(); // 重新加载旅客列表
                    } else {
                        alert(response.message || '删除失败');
                    }
                },
                error: function (xhr) {
                    alert('删除失败：' + (xhr.responseText || '服务器错误'));
                }
            });
        }
    };
    // 编辑旅客
    window.editTraveler = function (id) {
        // 跳转到编辑页面
        window.location.href = 'editTraveler.jsp?id=' + id;
    };
    // 设置默认旅客
    window.setDefault = function (id) {
        $.ajax({
            url: 'setDefaultTraveler',
            method: 'post',
            data: {id: id},
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    alert('设置成功');
                    loadTravelers(); // 重新加载列表
                } else {
                    alert(response.message || '设置失败');
                }
            },
            error: function (xhr) {
                alert('设置失败：' + (xhr.responseText || '服务器错误'));
            }
        });
    };

    // 优化后的加载动画
    function showLoading() {
        const container = $('.travelers-content');
        let html = '<div class="travelers-header">' +
            '<button class="add-btn" onclick="window.location.href=\'addtravelers.jsp\'">+ 新增常用旅客</button>' +
            '<div class="search-box">' +
            '<input type="text" class="search-input" placeholder="请输入姓名">' +
            '<button class="search-btn">搜索</button>' +
            '</div>' +
            '</div>' +
            '<div class="loading-state">' +
            '<div class="spinner"></div>' +
            '<p>正在加载数据...</p>' +
            '</div>';
        container.html(html);
    }

    function hideLoading() {
        $('.loading-state').remove();
    }
});
